/*
 * version_info.c
 *
 * Representación de información sobre la versión de kernel de Linux
 *
 */

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lexer.h"

#include "version_info.h"

VersionInfo version_info_new (const char *proc_dir) {
	VersionInfo result;
	FILE *f = NULL;
	bstring path = NULL;
	
	assert (proc_dir != NULL);
	
	path = bfromcstr (proc_dir);
	bcatcstr (path, "/sys/kernel/osrelease");
	f = fopen ((char *)path->data, "r");
	bdestroy (path);
	
	result.major = 0;
	result.minor = 0;
	result.subversion = 0;
	result.tag = bfromcstr ("");
	
	if (f != NULL) {
		Lexer *l = lexer_new (f);
		bstring s = NULL;
		
		lexer_next (l, DIGIT);
		s = lexer_item (l);
		result.major = atoi ((char *)s->data);
		bdestroy (s);
		lexer_skip (l, ".");
		
		lexer_next (l, DIGIT);
		s = lexer_item (l);
		result.minor = atoi ((char *)s->data);
		bdestroy(s); /*agregado por mi */
		lexer_skip (l, ".");
		
		lexer_next (l, DIGIT);
		s = lexer_item (l);
		result.subversion = atoi ((char *)s->data);
		bdestroy (s);
		
		lexer_next_to (l, "\n");
		bdestroy (result.tag); /* Liberar memoria del default */
		result.tag = lexer_item (l);

		lexer_destroy (l);
		fclose (f);
	}
	assert (result.tag != NULL);
	
	return result;
}

VersionInfo version_info_destroy (VersionInfo self) {
	bdestroy (self.tag); self.tag = NULL;

	return self;
}

